#include <REGX52.H>
#include <INTRINS.H>

sbit XPT2046_CS = P3^5;
sbit XPT2046_DCLK = P3^6;
sbit XPT2046_DIN = P3^4;
sbit XPT2046_DOUT = P3^7;

/** @bref XPT2046读取AD值
  * @param 命令字
  * @retval AD转换后的值，范围：8位为0~255，12位为0~4095
  */
unsigned int XPT2046_readAD(unsigned char command)
{
	unsigned char i = 0;
	unsigned int adValue = 0;
	
	XPT2046_DCLK = 0;
	XPT2046_CS = 0;

	for(i = 0; i < 8; i++)
	{
		XPT2046_DIN = command & (0x80 >> i);
		XPT2046_DCLK = 1;
		XPT2046_DCLK = 0;
	}
	
	for(i = 0; i < 16; i++)
	{
		XPT2046_DCLK = 1;
		XPT2046_DCLK = 0;
		if(XPT2046_DOUT)
		{
			adValue |= (0x8000 >> i);
		}
	}
	
	XPT2046_CS = 1;
	
	return adValue >> 8;
}
